/******************************************************************************
	This file is a part of the Snapshot Bioinformatics Project

	Copyright (C) 2012-2013 Jarom Schow

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#ifndef FILE_DOWNLOAD_H
#define FILE_DOWNLOAD_H

#include "BioDefs.h"

#include <QtCore/QObject>
#include <QtCore/QFile>

#include <QtNetwork/QNetworkReply>

namespace Bio {

class Progress;

class BIO_EXPORT FileDownload : public QObject {
	Q_OBJECT
public:
	FileDownload();
	FileDownload( const QString &filename );
	virtual ~FileDownload();

	void	setFilename( const QString &filename );

	bool	startDownload( const QString &url );
	bool	startDownload( const QUrl &url );

	bool	downloadSynchronous( const QString &url );
	bool	downloadSynchronous( const QUrl &url );

signals:

	void	finished();
	void	error( QNetworkReply::NetworkError code );
	void	downloadProgress( qint64 bytesReceived, qint64 bytesTotal );

private slots:

	void	dataReady();
	void	handleError( QNetworkReply::NetworkError code );
	void	handleProgress( qint64 bytesReceived, qint64 bytesTotal );
	void	finish();

private:

	bool	startup();
	bool	cleanup();

	QString			m_filename;
	QFile			m_file;
	QNetworkReply	*m_reply;
	char			*m_buffer;
	Progress		*m_progress;

	static QNetworkAccessManager	*s_mgr;
};

}; // Bio

#endif // FILE_DOWNLOAD_H